import { useState } from "react"
import Head from "next/head"
import PageLayout from "../../segments/PageLayout"

const nextInt = (max: number) => Math.floor(Math.random() * max)

const RandomStringToolPage: React.FC<Record<string, unknown>> = () => {
  const [upperRoma, setUpperRoma] = useState(true)
  const [lowerRoma, setLowerRoma] = useState(true)
  const [number, setNumber] = useState(true)
  const [other, setOther] = useState(false)
  const [otherBase, setOtherBase] = useState("~!@#$%^&*()[]{};':\",.<>/?-_")

  const [randomStr, setRandomStr] = useState("")
  const [randomStrLength, setRandomStrLength] = useState(17)

  const genRandomStr = () => {
    const base =
      (upperRoma ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "") +
      (lowerRoma ? "abcdefghijklmnopqrstuvwxyz" : "") +
      (number ? "0123456789" : "") +
      (other ? otherBase : "")
    let result = ""
    for (let i = 0; i < randomStrLength; i++) {
      result += base[nextInt(base.length)]
    }
    setRandomStr(result)
  }

  return (
    <PageLayout>
      <Head>
        <title>时间戳工具</title>
      </Head>
      <div style={{ width: 600, margin: "16px auto" }}>
        <input
          type="checkbox"
          checked={upperRoma}
          onChange={(e) => setUpperRoma(e.target.checked)}
        />
        &nbsp; 大写字母
        <br />
        <input
          type="checkbox"
          checked={lowerRoma}
          onChange={(e) => setLowerRoma(e.target.checked)}
        />
        &nbsp; 小写字母
        <br />
        <input type="checkbox" checked={number} onChange={(e) => setNumber(e.target.checked)} />
        &nbsp; 数字
        <br />
        <input type="checkbox" checked={other} onChange={(e) => setOther(e.target.checked)} />
        &nbsp; 其他字符：&nbsp;
        <input
          placeholder="请在此填写其他字符"
          value={otherBase}
          style={{ width: 360 }}
          onChange={(e) => setOtherBase(e.target.value)}
        />
        <br />
        随机字符串长度：
        <input value={randomStrLength} onChange={(e) => setRandomStrLength(+e.target.value)} />
        <br />
        <button onClick={genRandomStr}>生成随机字符串</button>
        <br />
        <code>{randomStr}</code>
      </div>
    </PageLayout>
  )
}

export default RandomStringToolPage
